<?php
/*
 * @Author: your name
 * @Date: 2021-12-29 09:18:45
 * @LastEditTime: 2022-03-03 22:19:12
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /nlog/swoole_server/Http.php
 */

//http服务

class Http
{
    private  $host  =  '0.0.0.0';
    private  $port  =  9501;
    public   $http  =  null;
    public function  __construct()
    {

        $this->http = new Swoole\Http\Server($this->host, $this->port);    //创建 swoole http服务
        $this->http->set([
            'enable_static_handler' => true,                              // 开启静态文件请求处理功能, 需配合document_root使用 用于文件访问 类似图片
            'document_root' => '/var/www/html/laravelStudy/nlog/public',   // 静态文件路径 
            'worker_num' => 4,                                          // swoole异步客户端的IO都是非阻塞的，属于CPU密集型操作。如果不清楚自己业务偏向于哪种类型，可设置进程数为CPU核数的2倍左右即可。
            // 'package_max_length'=>128,
        ]);
        $this->http->on('WorkerStart', [$this, "onWorkerStart"]);
        $this->http->on('Request', [$this, "onRequest"]);
       
        $this->http->start();
    }


    public function onWorkerStart($server,  $workerId)
    {

        define('LARAVEL_START', microtime(true));                                      //开启服务时自动加载

        defined('__URL__') or define('__URL__',  'http://192.168.157.128:' . $this->port);      //网站
        defined('__PATH__') or define('__PATH__', dirname(__DIR__) . '/public');                //目录
       
        //找商办
        defined('__WXAPPID__') or define('__WXAPPID__', "wx1c67e8d3d73b32f4");                          //微信小程序APPID
        defined('__WXAPPSECRET__') or define('__WXAPPSECRET__', "77562730b1d858f10a5179d15c232116");    //微信小程序APPSecret
        defined('__TTAPPID__') or define('__TTAPPID__', "tt065570e8996cd87401");                                //头条小程序APPID
        defined('__TTAPPSECRET__') or define('__TTAPPSECRET__', "9425226f3d39c2ea53950a33eba23fba3e3b914e");    //头条小程序APPSecret
       
        //每日兼职
        defined('__PARTIMEWXAPPID__') or define('__PARTIMEWXAPPID__', "wxa6fad0fcf2d79a33");                          //微信小程序APPID
        defined('__PARTIMEWXAPPSECRET__') or define('__PARTIMEWXAPPSECRET__', "17e31d9c0ce90db2b3e6e52e78d7a19f");    //微信小程序APPSecret
        defined('__PARTIMETTAPPID__') or define('__PARTIMETTAPPID__', "tt561220afc92b599a01");                                //头条小程序APPID
        defined('__PARTIMETTAPPSECRET__') or define('__PARTIMETTAPPSECRET__', "d60d9a64d4ec337479c3dd08f3d93771c1ec78e1");    //头条小程序APPSecret
         

        //redis 配置
        defined('REDIS_HOST') or define('REDIS_HOST', '127.0.0.1');    //IP地址 
        defined('REDIS_PASSWORD') or define('REDIS_PASSWORD', NULL);        //密码
        defined('REDIS_PORT') or define('REDIS_PORT', 6379);                //端口


        //mysql 配置

        defined('DB_HOST') or define('DB_HOST', '192.168.1.52');     //数据库ip地址
        defined('DB_PORT') or define('DB_PORT', 3306);                 //数据库端口
        defined('DB_DATABASE') or define('DB_DATABASE', 'property');   //数据库名称
        defined('DB_USERNAME') or define('DB_USERNAME', 'property');   //数据库账号
        defined('DB_PASSWORD') or define('DB_PASSWORD', 123456);       //数据库密码



       

       
      

        if (file_exists(__DIR__ . '/../storage/framework/maintenance.php')) {
            require __DIR__ . '/../storage/framework/maintenance.php';
        }
        //使用composer的自动加载
        require __DIR__ . '/../vendor/autoload.php';
    }

    public function onRequest($request, $response)
    {
        $this->setHeader( $response);   //设置跨域
       

        $_SERVER = []; //清理原有内存
        if (isset($request->server)) {
            foreach ($request->server as $k => $v) {
                $_SERVER[strtoupper($k)] = $v;
            }
        }
        if (isset($request->header)) {
            foreach ($request->header as $k => $v) {
                $_SERVER[strtoupper($k)] = $v;
            }
        }

        $_GET = [];  //清理原有内存
        if (isset($request->get)) {
            foreach ($request->get as $k => $v) {
                $_GET[$k] = $v;
            }
        }
        $_POST = [];  //清理原有内存
        if (isset($request->post)) {
            foreach ($request->post as $k => $v) {
                $_POST[$k] = $v;
            }
        }

        $_FILES = []; //清理原有内存
        if (empty($request->files)) {

            if (!empty($request->getContent())) {   //json数据
                //  file_put_contents( dirname(__DIR__).'/swoole_log/test.txt',$request->getContent().PHP_EOL,FILE_APPEND);
                $array = json_decode($request->getContent(), true);
                foreach ($array as $k => $v) {
                    $_POST[$k] = $v;
                }
            }
        } else {
            //文件上传
            foreach ($request->files as $k => $v) {
                $_FILES[$k] = $v;
            }
        }
        $_POST['HTTP_SERVER'] = $response;
        $_POST['HTTP_SERVER_REQUEST'] = $request;


        $app = new stdClass();   //清理原有内存
        $app = require __DIR__ . '/../bootstrap/app.php';          //注册http内核
        $kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);  //引导程序
        ob_start();
        //开启缓冲区 当打开输出缓存后，php的输出被重定向到内存。待程序结束后，再一并输出到客户端。
        //处理输入输出返回状态 
        try {
            $laravel_response = $kernel->handle(
                $laravel_request = Illuminate\Http\Request::capture()
            )->send();
        } catch (\Exception $e) {
            //todo
        }

        $res = ob_get_contents();      //获取并保存缓冲数据
        ob_end_clean();    //关闭缓冲区
        //terminate中间件

        $kernel->terminate($laravel_request, $laravel_response);
        $response->end($res);             //输出
    }


    public function setHeader( $response){
        $response->header('Access-Control-Allow-Origin', '*');
        $response->header('Access-Control-Allow-Methods', 'GET, POST, DELETE, PUT, PATCH, OPTIONS');
        $response->header('Access-Control-Allow-Headers', '*');
    }


  
}



new Http();
